package com.xiao.community.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiao.community.entity.PintuanEntity;
import com.xiao.community.service.PintuanService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiao.group.common.utils.PageUtils;
import com.xiao.group.common.utils.Query;

import com.xiao.community.dao.GoodsDao;
import com.xiao.community.entity.GoodsEntity;
import com.xiao.community.service.GoodsService;


@Service("goodsService")
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, GoodsEntity> implements GoodsService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private PintuanService pintuanService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<GoodsEntity> page = this.page(
                new Query<GoodsEntity>().getPage(params),
                new QueryWrapper<GoodsEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<GoodsEntity> selectByGoodsIfsale(int i) {

        return baseMapper.selectList(new QueryWrapper<GoodsEntity>().eq("goods_ifsale",i));
    }

    @Override
    public void addes() throws IOException {
        BulkRequest request = new BulkRequest();
        QueryWrapper<GoodsEntity> wrapper = new QueryWrapper<>();
        QueryWrapper<GoodsEntity> goods_ifsale = wrapper.eq("goods_ifsale", 1);
        List<GoodsEntity> entities = baseMapper.selectList(goods_ifsale);

        for (GoodsEntity entity : entities) {
            Integer goodsId = entity.getGoodsId();

            PintuanEntity pintuanEntity = pintuanService.selectByGoodsId(goodsId);
            String s = JSON.toJSONString(pintuanEntity);

            request.add(new IndexRequest("pintuan").id(pintuanEntity.getPintuanId().toString())
                    .source(s,XContentType.JSON));
        }

         client.bulk(request, RequestOptions.DEFAULT);
    }



}